package com.zyw.module.console.admin.auth;
/**
 * Created by qx on 2018/1/27.
 */

import com.zyw.module.console.qywx.api.AccessTokenApi;
import com.zyw.module.console.qywx.api.response.WxUserDeatilResponse;
import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 企业微信认证服务
 */
@Component
public class QywxAuthService implements AuthService {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(QywxAuthService.class);
    private static final String LOGIN_QYWXSTATUS_ATTRKEY = "status";

    @Override
    public String getCredentials(Object principal) {

        Object status = SecurityUtils.getSubject().getSession().getAttribute(LOGIN_QYWXSTATUS_ATTRKEY);
        return (String) status;
    }

    @Override
    public AuthInfo getAuthInfo(Object principal) {
        if (StringUtils.isEmpty(principal)) {
            //没有返回code,拒绝往下执行
            return null;
        }
        WxUserDeatilResponse wxUser = null;
        try {
            wxUser = AccessTokenApi.getUserInfoDetail((String) principal);
        } catch (Exception e) {
            log.error("访问微信服务器异常.");
            return null;
        }
        //请求到用户信息,说明用户存在,让用户认证登录成功
        //没有用户信息,拒绝登录
        if (wxUser == null) {
            return null;
        }

        AuthInfo authInfo = new AuthInfo();
        authInfo.setUsername(wxUser.getName());
        return authInfo;
    }

    @Override
    public boolean validCredentials(String principal, String targetCredentials, String sourceCredentials) {

        if (StringUtils.isEmpty(sourceCredentials)) {
            sourceCredentials = getCredentials(principal);
        }

        boolean e = StringUtils.equals(targetCredentials, sourceCredentials);

        if (e) {// 验证通过，清除session中的验证码信息
            SecurityUtils.getSubject().getSession().removeAttribute(LOGIN_QYWXSTATUS_ATTRKEY);
        }

        return e;
    }


    /**
     * 生成企业微信二维码的status字段
     */
    public String genatorQywxStatus() {
        SecurityUtils.getSubject().getSession().setAttribute(LOGIN_QYWXSTATUS_ATTRKEY, "123456");
        return "123456";

    }
}


